
 /**
  * @(#)DatabaseConfigProperties.java   2013-4-9
  * Copyright 2013  it.kedacom.com, Inc. All rights reserved.
  */
 
package com.kedacom.demo.emailgateway.core.annotation;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * 读取 数据库 t_sys_cfg
 * @author <a href="mailto:qianmingzhao@kedacom.com">qianmingzhao</a>
 * @date 2013-4-9下午02:18:20
 * @version 2.5.2
 */

public class DatabaseConfigProperties implements InitializingBean, FactoryBean<Object> {

	private static final Log log = LogFactory.getLog(DatabaseConfigProperties.class);
	private Properties props = new Properties();
	private DataSource datasource; // 数据源
	private String query; // 读取的sql

	public DatabaseConfigProperties(DataSource datasource, String query) {
		this.datasource = datasource;
		this.query = query;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		initProperties();
	}

	@Override
	public Object getObject() throws Exception {
		return props;
	}

	@Override
	public Class<Properties> getObjectType() {
		return Properties.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	// ----------

	private void initProperties() {
		Connection connection = null;
		try {
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/conf/jdbc.properties");    
			   Properties p = new Properties();    
			  try {    
			    p.load(inputStream);    
			   } catch (IOException e1) {    
			    e1.printStackTrace();    
			   } 
			String apUrl=p.getProperty("ap.url");
			String apUserName=p.getProperty("ap.username");
			String apPassword=p.getProperty("ap.password");
			
			Class.forName("org.gjt.mm.mysql.Driver").newInstance();
			connection= DriverManager.getConnection(apUrl, apUserName, apPassword);		
			PreparedStatement ps = connection.prepareStatement(query);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				String key = rs.getString(1);
				String value = rs.getString(2);
				if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
					log.info("load property. Key=" + key + ",Value=" + value);
					props.setProperty(key, value);
				}
			}
			rs.close();
			ps.close();
		} catch (Exception e) {
			log.error(e);
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception e) {
					log.error(e);
				}
			}
		}
	}
}

